import { Router } from 'express';
import crypto from 'crypto';
import { models } from '../db';

const router = Router();
const { account: AccountModel, user: UserModel, auth: AuthModel } = models;

router.post(
  '/account/login',
  async (
    req: { body: { account: string; password: string } },
    res: { send: (arg: string) => void; json: (arg: any) => void },
  ) => {
    const { account, password } = req.body;

    let md5 = crypto.createHash('md5');
    let newPassword = md5.update(password + 'xxsg').digest('hex');

    try {
      const accountInfo = await AccountModel.findOne({
        where: {
          account,
          password: newPassword,
        },
      });

      if (!accountInfo) {
        return res.json({ code: 0, msg: '账号或密码错误', data: {} });
      }

      const { id: accountId, is_actived, is_enabled } = accountInfo.dataValues;

      if (!is_actived) {
        return res.json({ code: 0, msg: '账号未激活，请联系管理员', data: {} });
      }

      if (!is_enabled) {
        return res.json({ code: 0, msg: '账号已被禁用，请联系管理员', data: {} });
      }

      const userInfo = await UserModel.findOne({
        where: {
          account_id: accountId,
        },
      });

      if (!userInfo) {
        return res.json({ code: 0, msg: '用户不存在', data: {} });
      }

      const { id: userId } = userInfo.dataValues;
      const token = crypto.randomBytes(32).toString('hex');

      await AuthModel.upsert({
        token,
        user_id: userId,
      });

      return res.json({
        code: 1,
        msg: '登陆成功',
        // data: { token: token, ws: 'ws://127.0.0.1:8888' },
        data: { token: token, ws: 'ws://www.xxsg.online:9999' },
      });
    } catch (error) {
      return res.json({ code: 0, msg: error, data: {} });
    }
  },
);

export default router;
